<template>
  <div>
    <el-card class="permission_main">
      <!-- 搜索框 -->
      <HeadAdd
        :addText="'新增'"
        :addTitle="'权限组'"
        @addClick="showDialogClick"
      >
        <template #search>
          <HeadSearch
            :searchText="query"
            @search="searchTitle"
            @clear="clearTitle"
          />
        </template>
      </HeadAdd>
      <!-- 警告框 -->
      <el-alert
        :title="`共 ${total} 条记录`"
        type="info"
        show-icon
        :closable="false"
        class="alert"
      />
      <!-- 表格 -->
      <el-table :data="permissionsList" v-loading="loading" style="width: 100%">
        <el-table-column type="selection" width="55px" />
        <el-table-column
          prop="title"
          label="用户名"
          align="center"
          width="750px"
        />
        <el-table-column
          prop="name"
          label="日期"
          sortable
          align="left"
          width="500px"
        >
          <template v-slot="{ row }">
            <span>{{ row.create_date | format }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" align="center">
          <template v-slot="{ row }">
            <el-button
              type="primary"
              icon="el-icon-edit"
              plain
              circle
              @click="showDialogClick('编辑', row.id)"
            />
            <el-button
              type="danger"
              icon="el-icon-delete"
              plain
              circle
              @click="delPermission(row.id)"
            />
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <FootPage :current="query" :total="total" @getList="clearTitle" />
    </el-card>
    <!-- 对话框 -->
    <el-dialog
      :title="`${text}权限组`"
      :visible.sync="showDialog"
      @close="btnCancel"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        style="width: 400px; margin: 0 auto"
      >
        <el-form-item label="用户名" prop="title">
          <el-input v-model="ruleForm.title" />
        </el-form-item>
        <el-form-item label="权限分配" prop="permissions">
          <el-tree
            ref="tree"
            :props="props"
            show-checkbox
            :data="menusList"
            node-key="id"
            :default-expanded-keys="[0]"
            :default-checked-keys="ruleForm.permissions"
            @check="checkedChange"
          >
          </el-tree>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        style="width: 400px; margin: 0 auto; text-align: center"
      >
        <el-button @click="btnCancel">取消</el-button>
        <el-button type="primary" @click="btnOk">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { required } from '@/module-manage/utils/index.js'
import HeadAdd from '@/module-manage/components/head-add'
import HeadSearch from '@/module-manage/components/head-search'
import FootPage from '@/module-manage/components/foot_page'
import { list, add, detail, update, remove } from '@/api/base/permissions.js'
import { list as menusList } from '@/api/base/menus.js'
export default {
  name: 'Permissions',
  components: { HeadAdd, HeadSearch, FootPage },
  data () {
    return {
      query: {
        page: 1,
        pagesize: 10,
        username: ''
      },
      total: 0,
      permissionsList: [],
      loading: false,
      showDialog: false,
      text: '',
      ruleForm: { title: '', permissions: [] },
      id: '',
      rules: { title: [required('用户名')] },
      menusList: [{ title: '系统菜单和页面权限点', children: [], id: 0 }],
      props: { label: 'title' },
      nodes: false
    }
  },
  filters: {
    format (value) {
      const date = new Date(value)
      const y = date.getFullYear()
      const m = (date.getMonth() + 1 + '').padStart(2, '0')
      const d = (date.getDate() + '').padStart(2, '0')
      return `${y}-${m}-${d}`
    }
  },
  created () {
    this.getPermissionsList({
      page: this.query.page,
      pagesize: this.query.pagesize
    })
  },
  methods: {
    // 获取页面数据
    async getPermissionsList (query) {
      try {
        this.loading = true
        const { data } = await list(query)
        this.permissionsList = data.list
        this.total = data.counts
        this.loading = false
      } catch (e) {
        this.loading = false
      }
    },
    // 搜索
    searchTitle () {
      this.getPermissionsList({
        page: this.query.page,
        pagesize: this.query.pagesize,
        title: this.query.username
      })
    },
    // 清除
    clearTitle () {
      this.getPermissionsList({
        page: this.query.page,
        pagesize: this.query.pagesize
      })
    },
    // 处理数据
    setMenusList (list) {
      list.forEach((item) => {
        if (item.childs) {
          item.children = item.childs
          this.setMenusList(item.children)
        } else if (item.points) {
          item.children = item.points
          this.setMenusList(item.children)
        }
      })
    },
    // 添加编辑
    async showDialogClick (text, id) {
      const { data } = await menusList()
      this.setMenusList(data)
      this.menusList[0].children = data
      if (this.nodes) {
        this.$refs.tree.setCheckedNodes(this.ruleForm.permissions)
      }
      this.nodes = true
      if (id) {
        this.id = id
        const res = await detail({ id: id })
        this.ruleForm.title = res.data.title
        this.ruleForm.permissions = res.data.permissions
      }
      this.text = text
      this.showDialog = true
    },
    // 点击复选框时触发
    checkedChange (data, checked) {
      this.ruleForm.permissions = checked.checkedKeys
    },
    // 取消
    btnCancel () {
      this.showDialog = false
      this.$refs.ruleForm.resetFields()
      this.id = ''
      this.ruleForm = {
        title: '',
        permissions: []
      }
    },
    // 提交
    async btnOk () {
      await this.$refs.ruleForm.validate()
      if (this.ruleForm.permissions.length === 0) {
        this.$message.warning('请选择权限分配')
        return
      }
      if (this.id !== '') {
        await update({ ...this.ruleForm, id: this.id })
        this.$message.success('编辑权限组成功')
      } else {
        await add(this.ruleForm)
        this.$message.success('创建权限组成功')
      }
      this.getPermissionsList({
        page: this.query.page,
        pagesize: this.query.pagesize
      })
      this.btnCancel()
    },
    async delPermission (id) {
      this.$confirm('此操作将永久删除用户 , 是否继续?')
        .then(async () => {
          await remove({ id: id })
          this.$message.success('删除用户成功')
          this.getPermissionsList({
            page: this.query.page,
            pagesize: this.query.pagesize
          })
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    }
  }
}
</script>

<style scoped lang="less">
.permission_main {
  margin: 20px;
  .alert {
    margin-bottom: 15px;
  }
}
</style>
